package com.tianquan.server.handler;

import com.tianquan.common.instance.ServiceInstance;
import com.tianquan.common.message.DeleteInstanceMessage;
import com.tianquan.common.message.ServiceUpdateMessage;
import com.tianquan.server.registry.ServerInstanceManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;


/**
 *@Author: tianquan
 *@date: 2024-11-03  20:58
 *@Description: 删除实例
 */
@Slf4j
@ChannelHandler.Sharable
public class DeleteInstanceMessageHandler extends SimpleChannelInboundHandler<DeleteInstanceMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DeleteInstanceMessage deleteInstanceMessage) throws Exception {
        // 删除对应实例
        log.info("-------------------服务下线删除服务---------------: {}", deleteInstanceMessage.getServiceName());
        String serviceName = deleteInstanceMessage.getServiceName();
        String id = deleteInstanceMessage.getId();
        ServerInstanceManager.removeInstance(serviceName, id);
        // // 发送最新实例列表
        Map<String, Set<ServiceInstance>> instances = ServerInstanceManager.getInstances();
        ServiceUpdateMessage serviceUpdateMessage = new ServiceUpdateMessage(true, null,instances);
        channelHandlerContext.writeAndFlush(serviceUpdateMessage);
    }
}
